package com.sw.c.controller;

import com.sw.c.enums.JwEnum;
import com.sw.c.mapper.TestMapper;
import com.sw.c.utils.ExcelUtils;
import com.sw.c.utils.SqlGenerator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Slf4j
@Api(tags = "读取excel创建表")
@RestController
@RequestMapping("/create")
public class CreateController {



    @Resource
    private TestMapper testMapper;

    @ApiOperation("读取excel创建表")
    @GetMapping("/sql")
    public String cj() {
        // 创建一个线程池，最大容量为30
        ExecutorService executorService = Executors.newFixedThreadPool(30);
        int i = 0;
        for (JwEnum jwEnum : JwEnum.values()) {
            String sheetName = jwEnum.getKey();
            Integer value = jwEnum.getValue();

            // 将任务提交给线程池执行
            executorService.submit(() -> createTableFromExcel(sheetName, value));
            i+=1;
        }

        // 关闭线程池：等待所有任务执行完毕
        shutdownAndAwaitTermination(executorService);
        return "表创建成功";
    }


    private void createTableFromExcel(String sheetName, Integer value) {
        try {
            Object[] result = ExcelUtils.excelRow("file/jw.xlsx", sheetName, value);

            // 获取拼音结果
            StringBuilder fields = (StringBuilder) result[0];
            // 获取中文结果
            StringBuilder chfields = (StringBuilder) result[1];

            String fieldData = fields.toString(); // 字段名数据
            String fieldComment = chfields.toString(); // 字段中文注释数据

            // 生成SQL语句
            String sql = SqlGenerator.generateCreateTableSql(sheetName, fieldData, fieldComment);
            log.info("sheet页对应sql见表语句：\n{}", sql);

            // 执行SQL语句创建表
            testMapper.create(sql);
            log.info(sheetName + "表创建成功");
            // 延时3秒
            Thread.sleep(3000);
        } catch (Exception e) {
            log.error("在创建数据表时出现异常,参数：{}, 错误：{}", sheetName, e);
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
//        String pinyin = ExcelUtils.convertToPinyin("律师");
//        log.info("pinyin:{}",pinyin);


        CreateController c = new CreateController();
        c.createTableFromExcel("教基综4900",1);
//        for (JwEnum jwEnum : JwEnum.values()) {
//            System.out.println("Key: " + jwEnum.getKey() + ", Value: " + jwEnum.getValue());
//        }
    }


    /**
     * 等待所有任务完成，最多等待60秒
     * @param pool
     */
    private void shutdownAndAwaitTermination(ExecutorService pool) {
        pool.shutdown(); // 启动一个平稳关闭过程
        try {
            // 等待所有任务完成，最多等待60秒
            if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
                pool.shutdownNow(); // 如果60秒内还没有结束，强制关闭
                if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
                    log.error("线程池无法关闭");
                }
            }
        } catch (InterruptedException e) {
            pool.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }
}
